package com.demo.util;

import com.jfinal.core.BaseController;
import com.jfinal.core.Controller;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.commons.io.FileUtils;



import com.alibaba.fastjson.JSON;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;
import org.apache.log4j.Logger;

/**
 * Created with IntelliJ IDEA.
 * User: xiaojing
 * Date: 14-8-2
 * Time: 下午4:40
 * To change this template use File | Settings | File Templates.
 */
public class UploadController extends BaseController {
    private static String filePath ="";
    /**
     *判断filePhth路径中是否存在该文件夹，不存在则创建该文件夹
     *创建成功则返回True
     * @param filePhth
     * @return
     **/

    static{
        Properties r = PropertiesHelper.loadProperty("/upload.properties");
        if(!r.isEmpty()){
            try{
                filePath = r.getProperty("filePaths");
            }catch(Exception e){
                Logger.getLogger(Upload.class).error("无法读filePath参数",e);
            }
           }else{
            Logger.getLogger(Upload.class).error("无法读取 upload.properties");
        }
    }

    /**
     * 文件上传
     * @throws Exception
     */
    public void upload() throws Exception{
        //定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,pdf");

        Map  result = new HashMap();
        String dirName = getPara("dir")==null?"image":getPara("dir");
        String realpath = getRequest().getRealPath("/"+filePath);
        UploadFile uf= getFile("imgFile",realpath);
        String affix_id = "";
        String affix_name = "";
        String archivesfileid=getPara("archivesfileid");
        if(uf!=null){
            affix_name = uf.getFile().getName();
            File file = uf.getFile();
            //检查扩展名
            System.out.println("affix_name------"+affix_name);
            String fileExt = affix_name.substring(affix_name.lastIndexOf(".") + 1).toLowerCase();

            if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
                result.put("error", 1);
                result.put("message", "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
                file.delete();
            }else{
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                affix_id = df.format(new Date()) + "_" + new Random().nextInt(1000)+"."+fileExt;
                System.out.println("affix_id------"+affix_id);
           
    	//		int id = xx.get("id");
                File savefile = new File(new File(realpath),affix_id);
                FileUtils.copyFile(file, savefile);
                if(file.exists()){
                    file.delete();
                }
                result.put("error", 0);
                result.put("title", affix_name);
                //linux文件路径应该为"\"
                result.put("url", JFinal.me().getContextPath()+"/"+filePath+"/"+affix_id);
            }
        }else{
            result.put("error", 1);
            result.put("message", "请选择文件");
        }
        render(new JsonRender(JSON.toJSONString(result)).forIE());
    }
    

    /**
     * 文件管理
     */
    public void manageImg(){
        String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};
        String currentPath = getRequest().getRealPath("/"+filePath)+File.separator ;
        File currentPathFile = new File(currentPath);
        List<Hashtable> fileList = new ArrayList<Hashtable>();
        if(currentPathFile.listFiles() != null) {
            for (File file : currentPathFile.listFiles()) {
                Hashtable<String, Object> hash = new Hashtable<String, Object>();
                String fileName = file.getName();
                if(file.isDirectory()) {
                    hash.put("is_dir", true);
                    hash.put("has_file", (file.listFiles() != null));
                    hash.put("filesize", 0L);
                    hash.put("is_photo", false);
                    hash.put("filetype", "");
                } else if(file.isFile()){
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    hash.put("is_dir", false);
                    hash.put("has_file", false);
                    hash.put("filesize", file.length());
                    hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));
                    hash.put("filetype", fileExt);
                }
                hash.put("filename", fileName);
                hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
                fileList.add(hash);
            }
        }
        //排序形式，name or size or type
        String order = getPara("order") != null ? getPara("order").toLowerCase() : "name";

        Map result = new HashMap();
        result.put("moveup_dir_path", "");
        result.put("current_dir_path","");
        result.put("current_url", JFinal.me().getContextPath()+"/"+filePath+"/");
        result.put("total_count", fileList.size());
        result.put("file_list", fileList);
        System.out.println(JSON.toJSONString(result));
        renderJson(JSON.toJSONString(result));
    }
    
    /**
     * 文件删除
     */
    public void delfile() {
        String filename = getPara("filename");

        String id = getPara("ids");
        String file = getRequest().getRealPath("/" ) + filename;
        File f = new File(file);
        // 路径为文件且不为空则进行删除
        if (Db.deleteById("oa_archivesfile", id)) {
            //删除文件
            if (f.isFile() && f.exists()) {
                f.delete();
                //
                renderJson(Constants.DELETESUCCESS);
            } else {
                renderJson(Constants.DELETEFAILED);
            }
        } else {
            renderJson(Constants.DELETEFAILED);
        }
    }
}
